<?php

namespace App\Core\Database;

class CacherManager
{
    public $cachers;

    protected $query;

    protected $defaultCacher = 'string';

    protected $prefix = '';

    protected $expire = 3600;

    public function __construct($query, $prefix = '', $expire = 3600)
    {
        $this->query = $query;
        $this->prefix = $prefix;
        $this->expire = $expire;
    }

    public function query($name = null)
    {
        $name = $name ?: $this->getDefaultCacher();

        return $this->cachers[$name] = $this->find($name);
    }

    protected function find($name)
    {
        return $this->cachers[$name] ?? $this->resolve($name);
    }

    public function getDefaultCacher()
    {
        return $this->defaultCacher;
    }

    public function setDefaultCacher($cacher = 'string')
    {
        $this->defaultCacher = $cacher;

        return $this;
    }

    protected function resolve($name)
    {
        $creator = 'create' . ucfirst($name) . 'Cacher';

        return $this->$creator()->setExpire($this->expire)->setPrefix($this->prefix);
    }

    protected function createStringCacher()
    {
        return new StringCacher($this->query);
    }

    protected function createHashCacher()
    {
        return new HashCacher($this->query);
    }

    protected function createSqlCacher()
    {
        return new SqlCacher($this->query);
    }

    public function setExpire($seconds = 3600)
    {
        $this->expire = $seconds;
    }

    public function setPrefix($prefix = '')
    {
        $this->prefix = $prefix;
    }

    public function __call($method, $arguments)
    {
        return $this->query()->$method(...$arguments);
    }
}
